package com.ilovepostcard.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.ilovepostcard.EditProfileActivity;
import com.ilovepostcard.PrintChooseCityActivity;
import com.ilovepostcard.R;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.UserController;
import com.ilovepostcard.controller.server.IServer;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.controller.server.ServerSpec;
import com.ilovepostcard.model.User;
import com.ilovepostcard.utils.Constants;
import com.ilovepostcard.utils.DateUtil;
import com.ilovepostcard.utils.DrawableManager;
import com.ilovepostcard.utils.ImageUtil;
import com.ilovepostcard.utils.StringUtils;
import com.ilovepostcard.utils.Utils;

public class EditProfileView extends LinearLayout {

    User mUser;
    Bitmap mHeadBitmap;
    boolean mCanModifyNickname;
    String mProvince = "";
    String mCity = "";
    String mCurrentNickname;
    
    ImageView user_head_imageview;
    EditText nick_eidt;
    EditText location_eidt;
    EditText birth_eidt;
    EditText intro_eidt;
    RadioView radio_male;
    RadioView radio_female;

    public EditProfileView(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate();
    }

    public EditProfileView(Context context) {
        super(context);
        inflate();
    }

    private View.OnClickListener sexRadioClick = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            radio_male.setChecked(v == radio_male);
            radio_female.setChecked(v == radio_female);
        }
    };

    private void inflate() {
        View view = View.inflate(getContext(), R.layout.edit_profile, this);
        user_head_imageview = (ImageView) view.findViewById(R.id.user_head_imageview);
        nick_eidt = (EditText) view.findViewById(R.id.nick_eidt);
        location_eidt = (EditText) view.findViewById(R.id.location_eidt);
        birth_eidt = (EditText) view.findViewById(R.id.birth_eidt);
        intro_eidt = (EditText) view.findViewById(R.id.intro_eidt);
        radio_male = (RadioView) view.findViewById(R.id.radio_male);
        radio_female = (RadioView) view.findViewById(R.id.radio_female);
        
        user_head_imageview.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                String[] arg0 = { getContext().getString(R.string.camera), getContext().getString(R.string.gallery) };
                Utils.showChooseDialog(getContext(), arg0, new Runnable[] {
                    new Runnable() {

                        @Override
                        public void run() {
                            ImageUtil.getImageFromCamera((Activity)getContext());
                        }
                        
                    },
                    new Runnable() {

                        @Override
                        public void run() {
                            ImageUtil.setImageFromGallery((Activity)getContext());
                        }
                        
                    }
                });
            }
        });

        location_eidt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Intent intent = new Intent(getContext(), PrintChooseCityActivity.class);
                    Activity activity = (Activity)getContext();
                    activity.startActivityForResult(intent, EditProfileActivity.REQUEST_CODE_CHOOSE_CITY);
                }
            }
        });
        location_eidt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PrintChooseCityActivity.class);
                Activity activity = (Activity)getContext();
                activity.startActivityForResult(intent, EditProfileActivity.REQUEST_CODE_CHOOSE_CITY);
            }
        });
        
        birth_eidt.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    Calendar calendar = DateUtil.display2calendar(birth_eidt.getEditableText().toString());
                    DatePickerDialog dpd = new DatePickerDialog(getContext(), new OnDateSetListener() {

                        @Override
                        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                            birth_eidt.setText(DateUtil.date2display(year, monthOfYear, dayOfMonth));
                        }
                    }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
                    dpd.show();
                }
            }
        });
        birth_eidt.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Calendar calendar = DateUtil.display2calendar(birth_eidt.getEditableText().toString());
                DatePickerDialog dpd = new DatePickerDialog(getContext(), new OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        birth_eidt.setText(DateUtil.date2display(year, monthOfYear, dayOfMonth));
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE));
                dpd.show();
            }
        });

        radio_male.setOnClickListener(sexRadioClick);
        radio_female.setOnClickListener(sexRadioClick);
        
        view.findViewById(R.id.save_profile).setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View v) {
                if (mUser == null)
                    return;
                new ServerAsyncTask(getContext()) {
                    
                    long uid = mUser.UserID;
                    int sex = radio_male.isChecked() ? 1 : (radio_female.isChecked() ? 2 : 0);
                    String birthday = DateUtil.display2server(birth_eidt.getText().toString());
                    String province = mProvince;
                    String city = mCity;
                    String introduction = intro_eidt.getEditableText().toString();
                    String editNickname = nick_eidt.getText().toString().trim();
                    String nickname = mCanModifyNickname ? ((editNickname.equals(mCurrentNickname)) ? "" : editNickname) : "";
                    
                    protected String getLoadingMessage() {
                        return "更新用户信息中。。。";
                    }
                    
                    @Override
                    protected void onSuccess(PostcardResult result) {
                        mUser.Sex = sex;
                        mUser.Birthday = birthday;
                        mUser.Province = province;
                        mUser.City = city;
                        mUser.Introduction = introduction;
                        mUser.Nickname = nick_eidt.getText().toString();
                        UserController.saveDetailUser(getContext(), mUser);
                        Toast.makeText(getContext(), "修改用户信息成功", Toast.LENGTH_SHORT).show();
                       
                        
                        
                        if (mHeadBitmap != null) {
                            /* need upload head image first */
                            new ServerAsyncTask(getContext()) {
                                
                                protected String getLoadingMessage() {
                                    return "上传头像中。。。";
                                }
                                
                                @Override
                                protected void onSuccess(PostcardResult result) {
                                    final String skey = result.getUploadSKey();
                                    new ServerAsyncTask(getContext()) {
                                        
                                        protected String getLoadingMessage() {
                                            return "上传头像中。。。";
                                        }
                                        
                                        @Override
                                        protected void onSuccess(PostcardResult result) {
                                            Toast.makeText(context, "上传头像成功", Toast.LENGTH_LONG).show();
                                            Activity activity = (Activity) getContext();
                                            activity.setResult(Activity.RESULT_FIRST_USER);
                                            activity.finish();
                                        }
                                        
                                        @Override
                                        protected PostcardResult doRequest() {
                                            File file = new File(Constants.APP_DIR);
                                            if (!file.exists()) {
                                                file.mkdirs();
                                            }
                                            File headImageFile = new File(file, "head.jpg");
                                            FileOutputStream fos = null;
                                            try {
                                                fos = new FileOutputStream(headImageFile);
                                                mHeadBitmap.compress(CompressFormat.JPEG, 100, fos);
                                            } catch (IOException e) {
                                                
                                            } finally {
                                                if (fos != null)
                                                    try { fos.close(); } catch (Exception e2) { }
                                            }
                                            if (headImageFile.exists() && headImageFile.length() > 0)
                                                return ServerFactory.getServer().uploadFile(IServer.FILE_TYPE_HEAD_IMAGE, "head_"+nickname+".jpg", skey, uid, 0, 0, 100, 100, 0, headImageFile);
                                            return null;
                                        }
                                    }.execute();
                                }
                                
                                @Override
                                protected PostcardResult doRequest() {
                                    return ServerFactory.getServer().getUploadSKey();
                                }
                            }.execute();
                        } else {
                            Activity activity = (Activity) getContext();
                            activity.setResult(Activity.RESULT_OK);
                            activity.finish();
                        }
                    }
                    
                    @Override
                    protected PostcardResult doRequest() {
                        return ServerFactory.getServer().updateUserInfo(uid, sex, birthday, province, city, introduction, nickname);
                    }
                }.execute();
            }
        });
    }

    public void setUser(final User user) {
        mUser = user;
        mCurrentNickname = user.Nickname;
        if (user.HasHeadImg)
            DrawableManager.getInstance().fetchDrawableOnThread(user.HeadImgUrl, user_head_imageview);
        nick_eidt.setText(user.Nickname);
        String displayDate = DateUtil.server2display(user.Birthday);
        birth_eidt.setText(displayDate);
        intro_eidt.setText(user.Introduction);
        radio_male.setChecked(user.Sex == ServerSpec.SexType.MALE);
        radio_female.setChecked(user.Sex == ServerSpec.SexType.FEMALE);
        setLocation(user.Province, user.City);
        new ServerAsyncTask(getContext()) {

            @Override
            protected void onSuccess(PostcardResult result) {
                mCanModifyNickname = result.canModifyNickname();
                nick_eidt.setEnabled(result.canModifyNickname());
            }

            @Override
            protected PostcardResult doRequest() {
                return ServerFactory.getServer().canModifyNickname(user.UserID);
            }
        }.execute();
    }
    
    public void setHeadImage(Bitmap head) {
        mHeadBitmap = head;
        user_head_imageview.setImageBitmap(head);
    }
    
    public void setLocation(String province, String city) {
        if (StringUtils.isNotEmpty(province) && StringUtils.isNotEmpty(city)) {
            mProvince = province;
            mCity = city;
            location_eidt.setText(province + " " + city);
        }
    }
}
